<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="main-nav">
          <div class="tree-style">
            <div class="search-box">
              <a-input-search
                v-model:value="searchDriver"
                placeholder="搜索"
                :allowClear="true"
                @search="onSearchDriver"
              />
            </div>
            <BasicTree
              title=""
              ref="treeRef"
              :treeData="treeDataPro"
              :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
              :onSelect="handleTreeSelect"
              :actionList="actionList"
            />
          </div>
        </div>
        <div class="main-content">
          <BasicTable @register="registerTable">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: '查看',
                      icon: 'ant-design:eye-filled',
                      ifShow: hasPermission('10-1-look'),
                      onClick: handleLook.bind(null, record),
                    },
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      ifShow: hasPermission('10-1-update'),
                      onClick: handleEdit.bind(null, record),
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      ifShow: hasPermission('10-1-del'),
                      onClick: handleDelete.bind(null, record),
                    },
                    {
                      label: '复制',
                      icon: 'ant-design:copy-outlined',
                      ifShow: hasPermission('10-1-copy'),
                      onClick: handleCopy.bind(null, record),
                    },
                  ]"
                />
              </template>
            </template>
            <template #toolbar>
              <a-button
                type="primary"
                @click="handleAdd"
                v-if="curInfo.Type === 2 && hasPermission('10-1-add')"
              >
                新增
              </a-button>
              <a-button type="primary" @click="handleSave" v-if="hasPermission('10-1-save')">
                保存到配置文件
              </a-button>
            </template>
          </BasicTable>
        </div>
      </div>
      <!-- 主机表单弹窗 -->
      <modelByServer
        :info="serverForm"
        :schemasProps="schemasByServer"
        :isDefaultFullscreen="true"
        @register="registerByServer"
        @handleSubmit="handleUpdateTree"
      />
      <!-- 表单弹窗 -->
      <modelByDetail
        :info="detailForm"
        :schemasProps="schemasByDetail"
        @register="registerByDetail"
        :modalOptions="modalOptions"
        :sendOptions="sendOptions"
        @handleSubmit="handleUpdateTable"
      />
      <!-- 分组弹窗 -->
      <modelByGroup
        :info="groupForm"
        @register="registerByGroup"
        @submit-success="handleUpdateTreePro"
      />
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useModal } from '/@/components/Modal';
  import { cloneDeep } from 'lodash-es';
  import modelByServer from '/@/views/project/rabbit/components/modelByServer.vue';
  import modelByDetail from '/@/views/project/rabbit/components/modelByDetail.vue';
  import modelByGroup from '/@/views/project/rabbit/components/modelByGroup.vue';

  import { FormSchema } from '/@/components/Form/index';

  import { reactive, ref, unref, onMounted, nextTick, h } from 'vue';
  import { BasicTree, TreeActionType, TreeActionItem } from '/@/components/Tree/index';
  import {
    getServerTree,
    delRabbiMQHost,
    getRabbiMQChannel,
    delRabbiMQChannel,
    getRoles,
    getSendMethod,
    saveConfig,
    addRabbiMQChannel,
    addRabbiMQHost,
    updateRabbiMQHost,
    updateRabbiMQChannel,
    delgroup,
    addgroup,
    editgroup,
    getRabbiMQHost,
  } from '/@/api/server/index';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { EyeOutlined, PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
  import { checkName, checkIp } from '/@/utils/index';
  import {
    rabbitServerParams,
    serverFormModel,
    serverFormDataModel,
    tableParamsModel,
    tableFormModel,
  } from './types/index';
  const treeRef = ref<Nullable<TreeActionType>>(null);
  let curInfo = reactive({});
  let treeDataPro = ref([]);
  let searchDriver = ref('');
  const { hasPermission } = usePermission();

  const actionList: TreeActionItem[] = [
    /**
     * Type 0 服务 1 主机 2分组
     *
     */
    {
      show: (node) => {
        return (
          ([0].indexOf(node.Type) >= 0 && hasPermission('10-1-addServer')) ||
          ([1].indexOf(node.Type) >= 0 && hasPermission('10-1-addGroup'))
        );
      },
      render: (node) => {
        return h(PlusOutlined, {
          class: 'ml-2',
          onClick: (e) => {
            e.stopPropagation();
            if (node.Type === 0) {
              // 添加主机
              handleAddServer();
            } else {
              // 添加分组
              groupForm.type = 'add';
              groupForm.data = node;
              openModalByGroup(true, {});
            }
          },
        });
      },
    },
    {
      show: (node) => {
        return node.Type === 1 && hasPermission('10-1-lookServer');
      },
      render: (node) => {
        return h(EyeOutlined, {
          class: 'ml-2',
          onClick: async (e) => {
            e.stopPropagation();
            serverForm.type = 'look';
            serverForm.data = await getFieldsValue(node);
            openModalByServer(true, {});
          },
        });
      },
    },
    {
      show: (node) => {
        return (
          ([1].indexOf(node.Type) >= 0 && hasPermission('10-1-updateServer')) ||
          ([2].indexOf(node.Type) >= 0 && hasPermission('10-1-updateGroup'))
        );
      },
      render: (node) => {
        return h(EditOutlined, {
          class: 'ml-2',
          onClick: async (e) => {
            e.stopPropagation();
            if (node.Type === 1) {
              loading.value = true;
              try {
                serverForm.type = 'update';
                serverForm.data = await getFieldsValue(node);
                openModalByServer(true, {});
                loading.value = false;
              } catch (error) {
                loading.value = false;
              }
            } else {
              groupForm.type = 'update';
              groupForm.data = node;
              openModalByGroup(true, {});
            }
          },
        });
      },
    },
    {
      show: (node) => {
        return (
          ([1].indexOf(node.Type) >= 0 && hasPermission('10-1-delServer')) ||
          ([2].indexOf(node.Type) >= 0 && hasPermission('10-1-delGroup'))
        );
      },
      render: (node: any) => {
        return h(DeleteOutlined, {
          class: 'ml-2',
          onClick: (e) => {
            e.stopPropagation();
            console.log(`output->node`, node);
            createConfirm({
              iconType: 'warning',
              okText: '确认',
              title: () => h('span', '温馨提示'),
              content: () =>
                h('span', `是否确认删除该${node.Type === 1 ? '服务' : '通道'}（${node.title}）`),
              onOk: async () => {
                try {
                  if (node.Type === 1) {
                    await delRabbiMQHost([node.title]);
                  } else {
                    await delgroup([node.Parentkey, node.title]);
                  }
                  createMessage.success(t('layout.setting.operatingTitle'));
                  initData();
                } catch (error) {}
              },
            });
          },
        });
      },
    },
  ];
  let schemasByServer: FormSchema[] = reactive([
    {
      field: 'name',
      component: 'Input',
      label: '名称：',
      helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',

      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '名称'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'virtualHost',
      component: 'Input',
      label: '虚拟主机：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入虚拟主机',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'hostIp',
      component: 'Input',
      label: '主机地址：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkIp(value, '主机地址'),
          trigger: ['change', 'blur'],
        },
      ],
    },

    {
      field: 'heartbeat',
      component: 'InputNumber',
      label: '心跳(s)：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入心跳',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'timeout',
      component: 'InputNumber',
      label: '请求超时(ms)：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入请求超时',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'port',
      component: 'Input',
      label: '端口：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请输入端口');
            }
            let reg = /^\+?[1-9]\d*$/;
            if (!reg.test(value)) {
              /* eslint-disable-next-line */
              return Promise.reject('只能输入正整数');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'recoveryInterval',
      component: 'TimePicker',
      label: '网络恢复间隔：',
      colProps: {
        span: 12,
      },
      componentProps: {
        style: 'width:100%',
        valueFormat: 'HH:mm:ss',
      },
      rules: [
        {
          required: true,
          message: '请输入网络恢复间隔',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'username',
      component: 'Input',
      label: '用户名：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入用户名',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'passagewayNum',
      component: 'InputNumber',
      label: '最大请求通道数：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入最大请求通道数',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'passport',
      component: 'Input',
      label: '密码：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'maxRequestNum',
      component: 'InputNumber',
      label: '请求帧最大值：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入请求帧最大值',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'prefix',
      component: 'Input',
      label: '通道前缀：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入通道前缀',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'reconnectionTime',
      component: 'InputNumber',
      label: '重连时间(ms)：',
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          message: '请输入重连时间',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'isTopology',
      component: 'RadioGroup',
      label: '是否启用拓扑恢复：',
      colProps: {
        span: 12,
      },
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否启用拓扑恢复', trigger: ['change', 'blur'] }],
    },
    {
      field: 'isAutomaticRecovery',
      component: 'RadioGroup',
      label: '是否启用自动恢复：',
      colProps: {
        span: 12,
      },
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否启用自动恢复', trigger: ['change', 'blur'] }],
    },
    {
      field: 'isUseIO',
      component: 'RadioGroup',
      label: '是否IO使用后台线程：',
      colProps: {
        span: 12,
      },
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否IO使用后台线程', trigger: ['change', 'blur'] }],
    },

    {
      field: 'isPassageway',
      component: 'RadioGroup',
      label: '是否启用主机：',
      colProps: {
        span: 12,
      },
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否启用主机', trigger: ['change', 'blur'] }],
    },

    {
      field: 'description',
      component: 'InputTextArea',
      label: '描述：',
      colProps: {
        span: 24,
      },
      componentProps: {
        showCount: true,
        maxlength: 200,
      },
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入描述',
      //     trigger: ['change', 'blur'],
      //   },
      // ],
    },
  ]);
  let schemasByDetail: FormSchema[] = reactive([
    {
      field: 'name',
      component: 'Input',
      label: '名称：',
      helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',

      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '名称'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'mode',
      component: 'Select',
      label: '方式：',
      colProps: {
        span: 24,
      },
      defaultValue: 0,
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择方式');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'CustomQueueName',
      component: 'Input',
      label: '自定义队列名称：',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入自定义队列名称',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'variable',
      component: 'Input',
      label: '关联变量：',
      slot: 'slotVariable',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入关联变量',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'method',
      component: 'Select',
      label: '发送方式：',
      colProps: {
        span: 24,
      },
      defaultValue: 0,
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择发送方式');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },

    {
      field: 'isPersistence',
      component: 'RadioGroup',
      label: '是否持久化:',
      colProps: {
        span: 24,
      },
      defaultValue: '1',
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否持久化', trigger: ['change', 'blur'] }],
    },
    {
      field: 'isOnly',
      component: 'RadioGroup',
      label: '是否独占:',
      colProps: {
        span: 24,
      },
      defaultValue: '2',
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否独占', trigger: ['change', 'blur'] }],
    },
    {
      field: 'isAutoDel',
      component: 'RadioGroup',
      label: '是否自动删除:',
      colProps: {
        span: 24,
      },
      defaultValue: '2',
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否自动删除', trigger: ['change', 'blur'] }],
    },

    {
      field: 'description',
      component: 'InputTextArea',
      label: '描述：',
      colProps: {
        span: 24,
      },
      componentProps: {
        showCount: true,
        maxlength: 200,
      },
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入描述',
      //     trigger: ['change', 'blur'],
      //   },
      // ],
    },
  ]);
  let groupForm = reactive({
    type: 'add',
    data: {},
    addgroup,
    editgroup,
  });
  let serverForm: serverFormModel = reactive({
    type: 'add',
    data: {},
  });
  let detailForm: any = reactive({
    type: 'add',
    data: {},
  });
  let modalOptions: any = reactive([]);
  let sendOptions: any = reactive([]);

  const loading = ref(false);
  const { createConfirm, createMessage } = useMessage();
  const { t } = useI18n();

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  let actionColumn = {
    width: 270,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };

  // 表单数据
  let columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'Name',
    },
    {
      title: '读写模式',
      dataIndex: 'RolesCn',
    },
    {
      title: '关联变量',
      dataIndex: 'TagName',
    },
    {
      width: 80,
      title: '发送方式',
      dataIndex: 'SendMethodCn',
    },
    {
      width: 90,
      title: '是否持久化',
      dataIndex: 'DurableCn',
    },
    {
      width: 77,
      title: '是否独占',
      dataIndex: 'ExclusiveCn',
    },
    {
      width: 110,
      title: '是否自动删除',
      dataIndex: 'IsAutoDeleteCn',
    },
    {
      title: '描述',
      dataIndex: 'Description',
      defaultHidden: true,
    },
  ];

  const [registerByServer, { openModal: openModalByServer, closeModal: closeModalByServer }] =
    useModal();
  const [registerByGroup, { openModal: openModalByGroup, closeModal: closeModalByGroup }] =
    useModal();
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerTable, { reload, setTableData }] = useTable({
    title: curInfo.title,
    api: getRabbiMQChannel,
    immediate: false,
    columns,
    pagination: false,
    actionColumn: hasPermission(['10-1-look', '10-1-update', '10-1-del', '10-1-copy'])
      ? actionColumn
      : undefined,
    canResize: false,
    showIndexColumn: false,
    striped: true,
    bordered: true,
    beforeFetch: () => {
      return [curInfo.Parentkey, curInfo.title];
    },
    afterFetch: (v) => {
      return v.map((item) => {
        item.IsAutoDeleteCn = item.IsAutoDelete ? '是' : '否';
        item.ExclusiveCn = item.Exclusive ? '是' : '否';
        item.DurableCn = item.Durable ? '是' : '否';
        let tagretRoles = modalOptions.filter((v) => +v.Value === +item.Roles);
        item.RolesCn = tagretRoles.length > 0 ? tagretRoles[0].Name : '';
        let tagretSend = sendOptions.filter((v) => +v.Value === +item.SendMethod);
        item.SendMethodCn = tagretSend.length > 0 ? tagretSend[0].Name : '';
        return item;
      });
    },
  });
  onMounted(async () => {
    try {
      modalOptions = await getRoles();
      sendOptions = await getSendMethod();
      initData(true);
    } catch (error) {}
  });
  async function getFieldsValue(val) {
    let resVal = await getRabbiMQHost([val.Key]);
    let params: serverFormDataModel = {
      virtualHost: resVal.VirtualHost,
      isPassageway: resVal.IsEnable ? '1' : '2',
      prefix: resVal.PublishPrefix,
      port: resVal.Port,
      username: resVal.UserName,
      passport: resVal.Password,
      timeout: resVal.RequestedConnectionTimeout,
      heartbeat: resVal.Heartbeat,
      isTopology: resVal.TopologyRecoveryEnabled ? '1' : '2',
      recoveryInterval: resVal.NetworkRecoveryInterval,
      isAutomaticRecovery: resVal.AutomaticRecoveryEnabled ? '1' : '2',
      isUseIO: resVal.UseBackgroundThreadsForIO ? '1' : '2',
      passagewayNum: resVal.ChannelMax,
      maxRequestNum: resVal.RequestedFrameMax,
      name: resVal.Name,
      description: resVal.Description || undefined,
      hostIp: resVal.HostIP,
      reconnectionTime: resVal.ContinuationTimeout || 0,
      OnlyName: val.Key,
    };
    return params;
  }
  function getFieldsValueByTable(val) {
    let setValue: tableFormModel = {
      serverName: val.serverName,
      mode: val.Roles,
      method: val.SendMethod,
      CustomQueueName: val.CustomQueueName,
      variable: val.TagName,
      isPersistence: val.Durable ? '1' : '2',
      isOnly: val.Exclusive ? '1' : '2',
      isAutoDel: val.IsAutoDelete ? '1' : '2',
      name: val.Name,
      description: val.Description,
      OnlyName: `${curInfo.Parentkey}.${val.GroupKey}.${val.Name}`,
    };
    return setValue;
  }
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveConfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  async function handleUpdateTable(res) {
    let params: tableParamsModel = {
      Roles: res.mode,
      SendMethod: res.method,
      TagName: res.variable,
      Durable: +res.isPersistence === 1,
      Exclusive: +res.isOnly === 1,
      CustomQueueName: res.CustomQueueName,
      IsAutoDelete: +res.isAutoDel === 1,
      Name: res.name,
      Description: res.description || '',
      GroupKey: curInfo.title,
    };
    if (detailForm.type === 'update') {
      await updateRabbiMQChannel([curInfo.Parentkey, detailForm.data.OnlyName, params]);
    } else {
      await addRabbiMQChannel([curInfo.Parentkey, params]);
    }
    createMessage.success(t('layout.setting.operatingTitle'));
    closeModalByDetail();
    setTimeout(() => {
      reload();
    }, 250);
  }
  async function handleUpdateTree(form) {
    let params: rabbitServerParams = {
      virtualHost: form.virtualHost,
      IsEnable: +form.isPassageway === 1,
      PublishPrefix: form.prefix,
      Port: form.port,
      UserName: form.username,
      Password: form.passport,
      RequestedConnectionTimeout: form.timeout,
      Heartbeat: form.heartbeat,
      TopologyRecoveryEnabled: +form.isTopology === 1,
      NetworkRecoveryInterval: form.recoveryInterval,
      AutomaticRecoveryEnabled: +form.isAutomaticRecovery === 1,
      UseBackgroundThreadsForIO: +form.isUseIO === 1,
      ChannelMax: form.passagewayNum,
      RequestedFrameMax: form.maxRequestNum,
      Name: form.name,
      ContinuationTimeout: form.reconnectionTime,
      Description: form.description || '',
      HostIP: form.hostIp,
    };
    if (serverForm.type === 'update') {
      await updateRabbiMQHost([serverForm.data.OnlyName, params]);
    } else {
      await addRabbiMQHost([params]);
    }
    createMessage.success(t('layout.setting.operatingTitle'));
    closeModalByServer();
    initData();
  }
  function handleUpdateTreePro() {
    closeModalByGroup();
    initData();
  }
  function eachTree(treeDatas: any[]) {
    treeDatas.forEach((element) => {
      element.title = element.Name;
      // switch (element.Type) {
      //   case 0:
      //     element.icon = 'ant-design:home-outlined';
      //     break;
      //   case 1:
      //     element.icon = 'ant-design:database-outlined';
      //     break;
      //   case 2:
      //     element.icon = 'ant-design:bars-outlined';
      //     break;
      //   case 3:
      //     element.icon = 'ant-design:folder-outlined';
      //     break;
      //   default:
      //     break;
      // }

      if (element.Children) eachTree(element.Children);
    });
  }
  // 搜索设备
  function onSearchDriver() {
    initData();
  }
  async function initData(isOpenTree = false) {
    loading.value = true;
    try {
      let resByTree = await getServerTree(searchDriver.value ? [searchDriver.value] : [null]);
      eachTree(resByTree);
      treeDataPro.value = resByTree || [];
      if (isOpenTree) {
        nextTick(() => {
          getTree().filterByLevel(1);
        });
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  function handleAddServer() {
    serverForm.type = 'add';
    serverForm.data = {};
    openModalByServer(true, {});
  }
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = { serverName: curInfo.title };
    openModalByDetail();
  }
  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '温馨提示'),
      content: () => h('span', `是否确认删除该通道（${record.Name}）`),
      onOk: async () => {
        try {
          await delRabbiMQChannel([
            curInfo.Parentkey,
            `${curInfo.Parentkey}.${record.GroupKey}.${record.Name}`,
          ]);
          createMessage.success(t('layout.setting.operatingTitle'));
          reload();
        } catch (error) {}
      },
    });
  }
  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    detailForm.type = 'update';
    detailForm.data = getFieldsValueByTable({
      serverName: curInfo.title,
      ...record,
    }) as tableFormModel;
    openModalByDetail();
  }
  function handleCopy(record: Recordable) {
    let params = cloneDeep(record);
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认复制该服务（${params.Name}）`),
      onOk: async () => {
        try {
          params.Name = `${params.Name}_copy`;
          await addRabbiMQChannel([curInfo.Parentkey, params]);
          createMessage.success(t('layout.setting.operatingTitle'));
          reload();
        } catch (error) {}
      },
    });
  }
  function handleLook(record: Recordable) {
    detailForm.type = 'look';
    detailForm.data = getFieldsValueByTable({
      serverName: curInfo.title,
      ...record,
    }) as tableFormModel;
    openModalByDetail();
  }
  function handleTreeSelect(_e, info) {
    if (info.node?.Type === 2) {
      curInfo = info.node;
      reload();
    } else {
      setTableData([]);
      curInfo = {};
    }
  }
</script>
<script lang="ts">
  export default {
    name: 'RabbitIndexPage',
  };
</script>
<style scoped lang="less">
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
  }

  .tag {
    position: relative;
    overflow: hidden;
    height: 100%;
    background-color: #fff;

    .main-nav {
      position: absolute;
      top: 0;
      left: 0;
      width: 240px;
      height: 100%;
      padding: 8px;
      box-sizing: border-box;
      overflow: auto;
      background-color: rgba(8, 30, 66, 0.04);
      border-radius: 3px;

      .tree-style {
        position: absolute;
        top: 0;
        left: 0;
        padding: 8px;
        width: 240px;
        z-index: 2;
        bottom: 0;
        box-sizing: border-box;
      }
    }

    .main-content {
      position: relative;
      height: 100%;
      margin-left: 260px;
      overflow: hidden;
    }
  }

  .add-server {
    width: 100%;
    position: relative;
    z-index: 5;
    margin-bottom: 10px;
  }
</style>
